package joshua.hibernate.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import joshua.hibernate.mapping.UserThreadEntity;

import org.hibernate.Query;

public class UserThreadDAO {

	public List findAll() {
		List<UserThreadEntity> allThread = (List<UserThreadEntity>)sessionDAO.createQuery("FROM UserThreadEntity").list();
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		for(UserThreadEntity thread: allThread) {
			Map<String, Object> entityDat = new HashMap<String, Object>();
			entityDat.put("userName", thread.getUserName());
			entityDat.put("detail", thread.getDetail());
			entityDat.put("threadId", thread.getThreadId());
			entityDat.put("updateDate", thread.getUpdateDate());
			res.add(entityDat);
		}
		return res;
	}
	
	
	public Serializable save(String userName, String detail, Date updateDate) {
		UserThreadEntity userThread = new UserThreadEntity();
		userThread.setDetail(detail);
		userThread.setUserName(userName);
		userThread.setUpdateDate(updateDate);
		sessionDAO.begin();
		Serializable saveId = sessionDAO.save(userThread);
		sessionDAO.commit();
		return saveId;
	}
	
	
	public void delete(int threadId) {
		UserThreadEntity userThread = findByPk(threadId);
		sessionDAO.begin();
		sessionDAO.delete(userThread);
		sessionDAO.commit();
	}
	
	
	public <T> T findByPk(int pk) {
		Query query = sessionDAO.createQuery("FROM UserThreadEntity WHERE threadId = :threadId");
		query.setInteger("threadId", pk);
		return (T)query.uniqueResult();
	}
	
	
	
	private SessionDAO sessionDAO = SessionDAO.newInstatnce();
	
	
	public static void main(String[] args){
		UserThreadDAO dao = new UserThreadDAO();
		dao.findAll();
	}
}
